<?php
/**
 * Created by PhpStorm.
 * User: 王世鹏
 * Date: 2018/3/14
 * Time: 14:39
 */

namespace app\back\controller;


use think\Config;
use think\Controller;
use think\Db;
use think\Exception;

class MakeController extends Controller
{
    private $input = [];
    private $fields = [];

    //数据表主页面显示
    public function tableAction()
    {

        return $this->fetch();
    }

    //显示表的信息
    public function infoAction()
    {
        $table_name = input("get.table_name");
        $table_name = Config::get("database.prefix") . $table_name;
        $db_name = Config::get("database.database");
        $sql = "SELECT TABLE_COMMENT FROM information_schema.`TABLES` WHERE TABLE_SCHEMA=? AND TABLE_NAME=?";
        $mark = Db::query($sql, [$db_name, $table_name]);
        $sql = "SELECT COLUMN_COMMENT,COLUMN_NAME FROM information_schema.`COLUMNS` WHERE TABLE_NAME=?  AND TABLE_SCHEMA=?";
        $fields = Db::query($sql, [$table_name, $db_name]);
        return [
            'comment' => $mark[0]["TABLE_COMMENT"],
            'fields' => $fields,
            'table_name' => $table_name
        ];

    }


    //自动生成表入口
    public function generateAction()
    {

       try{
           if (empty(input("post.field/a"))) $this->redirect("table");
           $this->input["table_name"] = input("table_name");
           $this->input["mark"] = input("mark");
           $this->input["fields"] = input("field/a");
           $this->makeController();
           $this->makeModel();
           $this->makeValidate();
           $this->makeViewIndex();
           $this->makeViewSet();
            $this->success('生成成功',$this->input["table_name"].'/index');

       }catch (Exception  $e){
           echo $e->getMessage();
       }
    }

    //替换操作
    private function replace($temp, $search, $replace, $file)
    {
        $temp = file_get_contents($temp);
        $content = str_replace($search, $replace, $temp);
        $dir = dirname($file);
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        file_put_contents($file, $content);
    }


    //生成视图首页
    private function makeViewIndex()
    {
        //搜索
        $temp_search = file_get_contents(APP_PATH . "back/code/view_search.php");
        $search_str = "";
        $count = 2;
        //排序
        $temp_table_header = file_get_contents(APP_PATH . "back/code/view_table_header.php");
        $temp_table_header_order = file_get_contents(APP_PATH . "back/code/view_table_header_order.php");
        $header_str = "";
        //内容
        $temp_table_header_data = file_get_contents(APP_PATH . "back/code/view_table_data.php");
        $data_str = "";
        foreach ($this->input["fields"] as $v) {
            if (isset($v["search"])) {
                $search = ["%label%", "%field%"];
                $replace = [$v["cname"], $v["name"]];
                $search_str .= str_replace($search, $replace, $temp_search);
            }
            if (isset($v["list"])) {
                if (isset($v["sort"])) {
                    $temp_table_header = $temp_table_header_order;
                } else {

                }
                $search = ["%label%", "%field%"];
                $replace = [$v["cname"], $v["name"]];
                $header_str .= str_replace($search, $replace, $temp_table_header);

                $search = ["%field%"];
                $replace = [$v["name"]];
                $data_str .= str_replace($search, $replace, $temp_table_header_data);
                $count++;
            }

        }

        $temp = APP_PATH . "back/code/viewIndex.php";
        $search = ["%table_title%", "%view_search%", "%view_table_header%", " %view_table_data%", "%count%"];
        $replace = [$this->input["mark"], $search_str, $header_str, $data_str, $count];

        $file = APP_PATH . "back/view/" . $this->input["table_name"] . "/index.html";
        $this->replace($temp, $search, $replace, $file);
        echo "视图生成完毕：" . $file . "<br/>";

    }

    //生成视图修改增加页
    private function makeViewSet()
    {
        $temp_input = file_get_contents(APP_PATH . "back/code/viewSetInput.php");
        $input_str = "";
        $require = "";
        foreach ($this->input["fields"] as $v) {
            if (isset($v["option"])) {
                if (isset($v["require"])) {

                    $require = "required";

                } else {

                }
                $search = ["%require%","%label%","%field%"];
                $replace = [$require,$v["cname"],$v["name"]];
                $input_str .= str_replace($search,$replace,$temp_input);

            } else {

            }
        }
        $temp =  APP_PATH ."back/code/viewSet.php";
        $search = ["%label%","%set_list%"];
        $replace = [$this->input["mark"],$input_str];
        $file = APP_PATH . "back/view/" . $this->input["table_name"] . "/set.html";
        $this->replace($temp,$search,$replace,$file);
        echo "视图修改:".$file."<br/>";
    }


    //生成模型
    private function makeModel()
    {
        $model = $this->mkModel();
        $temp = APP_PATH . "back/code/model.php";
        $search = ["%model%"];
        $file = APP_PATH . "back/model/" . $model . ".php";
        $this->replace($temp, $search, $model, $file);
        echo "模型完成了:" . $file . "<br/>";

    }

    //生成控制器
    private function makeController()
    {
        $con = $this->mkController();
        $model = $this->mkModel();
        $validate = $this->mkValidate();
        $temp = file_get_contents(APP_PATH . "back/code/indexwhere.php");
        $where_sort = "";
        foreach ($this->input["fields"] as $v) {
            if (!isset($v["search"])) continue;
            $search = "%field%";
            $replace = $v["name"];
            $content = str_replace($search, $replace, $temp);
            $where_sort .= $content;
        }

        $temp = APP_PATH . "back/code/controller.php";
        $search = ["%controller%", "%model%", "%validate%", "%where%"];
        $replace = [$con, $model, $validate, $where_sort];
        $file = APP_PATH . "back/controller/" . $con . ".php";
        $this->replace($temp, $search, $replace, $file);
        echo "控制器生成了：" . $file . "<br/>";


    }

    //生成规则器
    private function makeValidate()
    {
        $validate = $this->mkValidate();
        $field_list = "";
        $temp = file_get_contents(APP_PATH . "back/code/validateField.php");

        foreach ($this->input["fields"] as $v) {
            $search = ["%name%", "%comment%"];
            $replace = [$v["name"], $v["cname"]];
            $content = str_replace($search, $replace, $temp);
            $field_list .= $content;

        }

        $field_list = trim($field_list, ",");
        $temp = APP_PATH . "back/code/validate.php";
        $search = ["%validate%", "%field_list%"];
        $replace = [$validate, $field_list];
        $file = APP_PATH . "back/validate/" . $validate . ".php";
        $this->replace($temp, $search, $replace, $file);
        echo "规则器生成了：" . $file . "<br/>";
    }

    //格式化控制器名字
    private function mkController()
    {
        $table = $this->input["table_name"];

        if (!isset($this->fields["controller"])) {
            $this->fields["controller"] = implode(array_map('ucfirst', explode("_", $table))) . "Controller";
        }
        return $this->fields["controller"];


    }

    //格式化模型名字
    private function mkModel()
    {
        $table = $this->input["table_name"];
        if (!isset($this->fields["model"])) {
            $this->fields["model"] = implode(array_map('ucfirst', explode("_", $table)));
        }
        return $this->fields["model"];


    }

    //格式化规则器名字
    private function mkValidate()
    {
        $table = $this->input["table_name"];
        if (!isset($this->fields["validate"])) {
            $this->fields["validate"] = implode(array_map('ucfirst', explode("_", $table))) . "Validate";
        }
        return $this->fields["validate"];

    }


}